package com.wps.wdztv6.api.preview;

import com.alibaba.fastjson2.JSON;
import com.wps.wdztv6.api.request.PreviewPreloadRequest;
import com.wps.wdztv6.api.response.PreviewPreloadResponse;
import com.wps.wdztv6.api.response.PreviewResponse;
import com.wps.wdztv6.common.HttpPostUtil;
import com.wps.wdztv6.utils.WPS4Util;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import java.util.Map;

@Log4j2
public class WdztPreviewApi {

    public static final String CONTENT_TYPE = "application/json";

    public static final String[] FILE_TYPES = {"w","s","p","f","x"};

    public static PreviewResponse getPreviewUrl(String host, String fileId, String type, String wThirdParams) throws Exception {
        boolean isSupport = false;
        for(int i =0;i< FILE_TYPES.length;i++) {
            if (StringUtils.equals(FILE_TYPES[i],type)) {
                isSupport = true;
                break;
            }
        }
        if (!isSupport) {
            log.error("获取在线预览，文档类型不支持:"+type);
            throw new RuntimeException("获取在线预览，文档类型不支持:"+type);
        }
        String url = String.format("/api/preview/v1/files/%s/link?%s",fileId,wThirdParams);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.GET.toString(),null,CONTENT_TYPE);
        log.info("本次请求headers:{}", JSON.toJSONString(headers));
        return HttpPostUtil.sendGetRequest(host+url,headers,PreviewResponse.class);
    }

    /**
     * 预览预处理
     * @param host 文档中台地址
     * @param fileId 文件id
     * @param version 文件版本
     * @param callbackUrl 通知回调地址
     */
    public static PreviewPreloadResponse previewPreload(String host, String fileId, Integer version, String callbackUrl) throws Exception {
        String url = "/api/preview/v2/files/{file_id}/versions/{version_id}/preload";
        url = url.replace("{file_id}",fileId).replace("{version_id}",String.valueOf(version));
        PreviewPreloadRequest requestBody = PreviewPreloadRequest.builder().webhook(callbackUrl).build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,PreviewPreloadResponse.class);
    }
}
